package Solution125_150;

import common.ListNode;

import java.util.HashSet;
import java.util.Set;

public class Solution141 {
    public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null||head.next.next==null) {
            return false;
        }
        ListNode q=head.next.next;
        ListNode s=head.next;
        while (q!=null&&q.next!=null&&q.next.next!=null){
            if(q==s){
                return true;
            }
            q=q.next.next;
            s=s.next;
        }
        return false;
    }


    public boolean hasCycle2(ListNode head) {
        Set<ListNode> nodesSeen = new HashSet<>();
        while (head != null) {
            if (nodesSeen.contains(head)) {
                return true;
            } else {
                nodesSeen.add(head);
            }
            head = head.next;
        }
        return false;
    }
}
